package top.system.dept.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import top.system.dept.utils.NetWork;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.*;

/**
 * @ClassName: WechatService
 * @Author: Amosen
 * @Since: 2021/5/20
 */

@Service
public class WechatService {

    Logger logger = LoggerFactory.getLogger(WechatService.class);

    @Value("${mini.accessToken.url}")
    private String accessTokenURL;

    @Value("${mini.appid}")
    private String appid;

    @Value("${mini.secret}")
    private String secret;

    @Value("${mini.accessToken.grant_type}")
    private String accessTokenGrantType;

    @Value("${mini.notify.retryTimes}")
    private Integer sendNotifyRetryTimes;

    @Value("${mini.notify.send.url}")
    private String sendNotifyUrl;

    public String getAccessToken() {
        Map<String, String> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("grant_type", accessTokenGrantType);
        Map<String, Object> response = NetWork.service(accessTokenURL, HttpMethod.GET, params, null);
        try {
            return String.valueOf(response.get("access_token"));
        } catch (NullPointerException e) {
            logger.error("获取access_token失败！", e);
        }
        return "";
    }

    public void sendNotify(String notifyId, String toUser, String page, Map<String, String> datas) {
        // 封装通知下发参数
        Map<String, Map<String, String>> requestData = new HashMap<>();
        for (Entry<String, String> data : datas.entrySet()) {
            Map<String, String> valueMap = new HashMap<>();
            valueMap.put("value", data.getValue());
            requestData.put(data.getKey(), valueMap);
        }

        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("touser", toUser);
        requestParam.put("template_id", notifyId);
        requestParam.put("page", page);
        requestParam.put("data", requestData);


        Map<String, Object> response = NetWork.doPostWithJsonData(sendNotifyUrl + getAccessToken(), requestParam, null);
        logger.info("response =======>   ");
        for (Entry<String, Object> resp : response.entrySet()) {
            System.out.println(resp.getKey() + ": " + resp.getValue());
        }
    }
}
